/*
 * BasicLight.java
 * iRoomMonitor1.0
 * 11/13/10
 */
package RoomNanny.SpotSensors;

import com.sun.spot.sensorboard.EDemoBoard;
import com.sun.spot.sensorboard.io.IScalarInput;

import java.io.*;

/**
 * This class implements a basic light sensor. It calibrates for light
 * by reseting the max and min bounds of light according to the current
 * calibration reading.
 * 
 * @author Erin Griffiths
 */
public class BasicLight implements Light{

    private IScalarInput lightSensor = EDemoBoard.getInstance()
            .getLightSensor();
    private int lightMin;
    private int lightMax;

    /**
     * Returns the current light reading.
     *
     * @return int light
     * @throws IOException
     */
    public int getCurrent() throws IOException{
        return lightSensor.getValue();
    }

    /**
     * Calibrates light by reading the current light and updating the max and
     * min light values according to this reading.
     */
    public void calibrate(){
        long lightCalibrationStart = System.currentTimeMillis();

        // Give inital values to the min and max
        lightMax = 0;
        lightMin = 255;
        int lightReading = 0;

        // Calibrate for 5 seconds...
        while ((lightCalibrationStart + 5000) > System.currentTimeMillis()){
            try {
                lightReading = getCurrent();
            } catch (IOException e) {
                System.err.println("Failed to collect current temp");
            }

            // Update bounds
            if (lightReading > lightMax){
                lightMax = lightReading;
            }
            if (lightReading < lightMin){
                lightMin = lightReading;
            }
        }
    }

    /**
     * Returns the current upper bound of light.
     *
     * @return int max light
     */
    public int getMax(){
        return lightMax;
    }

    /**
     * Returns current lower bound of light.
     *
     * @return int min light
     */
    public int getMin(){
        return lightMin;
    }

}
